package com.demo.web.admin.exceptionhandler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.bluering.framework.common.log.Logger;
import com.demo.web.admin.form.FormResp;
import com.demo.web.admin.form.code.FormRespCode;

@ControllerAdvice
public class ControllerExceptionHanler {
	
	private static Logger logger =Logger.getLogger(ControllerExceptionHanler.class);
    
    @ExceptionHandler
    public void handleException(Exception exception, HttpServletRequest request,HttpServletResponse response) {
    	
        logger.error(exception.getMessage(), exception);
        
        FormResp form = new FormResp();
        form.setEcode(FormRespCode.REDIRECT);
        form.setRedirectUri(request.getContextPath()+"/error/404.html");
        form.setMessage(exception.getMessage());
        
        sendMessage(request,response,form);

        
    }
    
    private boolean isAjaxRequest(HttpServletRequest req) {
		boolean isAjaxRequest = false;
		if(!StringUtils.isBlank(req.getHeader("x-requested-with")) && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
            isAjaxRequest = true;
        }
		return isAjaxRequest;
	}
	
	private void sendMessage(HttpServletRequest request,HttpServletResponse response,FormResp form) {
		if(isAjaxRequest(request)) {
			response.setCharacterEncoding("UTF-8");  
		    response.setContentType("application/json; charset=utf-8");
		    PrintWriter out = null;  
		    try {
		        out = response.getWriter();
		        out.append(JSON.toJSONString(form));
		    } catch (IOException e) {
		       logger.error(e.getMessage(),e);
		    } finally {
		        if (out != null) {
		            out.close();
		        }
		    }
		}else {
			try {
				response.sendRedirect(form.getRedirectUri());
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
			}
		}
	}
	
}
